package com.sunshine.lnuplus.ui.fragment

import android.annotation.SuppressLint
import android.app.Service
import android.content.*
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.base.BaseFragment
import com.sunshine.lnuplus.callback.LoadDataCallBack
import com.sunshine.lnuplus.model.InitData
import com.sunshine.lnuplus.service.LoadFunctionService
import com.sunshine.lnuplus.ui.activity.*
import com.sunshine.lnuplus.utils.StatusBarUtils
import com.sunshine.lnuplus.utils.TagHelper
import com.sunshine.lnuplus.utils.UpdateWidgetUtils
import com.sunshine.lnuplus.view.DialogWithoutView
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.fragment_function.*

class FunctionFragment : BaseFragment() {

    private var conn: ServiceConnection? = null
    private lateinit var functionList: ArrayList<ArrayList<String>>

    companion object {
        fun newInstance() = FunctionFragment()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_function, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initView()
    }

    private fun initView() {
        initDefaultFunction()
        if(InitData.functionList != null){
            handler.sendEmptyMessage(1)
        }else{
            initFunction()
        }
    }

    private fun initFunction() {
        val intent = Intent(activity, LoadFunctionService::class.java)
        var loadFunctionService: LoadFunctionService
        conn = object : ServiceConnection {
            override fun onServiceDisconnected(name: ComponentName) {}
            override fun onServiceConnected(
                name: ComponentName,
                service: IBinder
            ) {
                loadFunctionService = (service as LoadFunctionService.MyBind).getService()
                loadFunctionService.setCallBack(object : LoadDataCallBack {
                    override fun onSuccess() {
                        functionList = loadFunctionService.getFunctionList()
                        InitData.functionList = functionList
                        handler.sendEmptyMessage(1)
                    }
                })
            }
        }
        activity?.bindService(intent, conn!!, Service.BIND_AUTO_CREATE)
    }

    private fun initDefaultFunction() {
        if(getTimetableTheme() == 1 && !context!!.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE).getBoolean("night", false)){
            function_text.setTextColor(Color.BLACK)
            button_score.setTextColor(Color.BLACK)
            button_school_date.setTextColor(Color.BLACK)
            button_calender.setTextColor(Color.BLACK)
            button_bandr.setTextColor(Color.BLACK)
            button_xiaoai.setTextColor(Color.BLACK)
        }
        button_score.setOnClickListener {
            startActivity(Intent(activity!!, SearchScoreActivity::class.java))
        }
        button_school_date.setOnClickListener {
            startActivity(Intent(activity!!, SchoolDateActivity::class.java))
        }
        button_calender.setOnClickListener {
            startActivity(Intent(activity!!, CalenderActivity::class.java))
        }
        button_bandr.setOnClickListener {
            startActivityForResult(Intent(activity!!, BandRActivity::class.java), TagHelper.FUNCTION)
        }
        button_xiaoai.setOnClickListener {
            startActivity(Intent(activity!!, XiaoAiActivity::class.java))
        }
    }

    override fun setContent(): Int {
        return R.layout.fragment_function
    }

    @SuppressLint("HandlerLeak")
    val handler = object : Handler(){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (1 == msg.what){
                InitData.functionList?.forEach { function ->
                    val view = LayoutInflater.from(context!!).inflate(R.layout.item_function_recycler_view, function_view, false)
                    val button: Button = view.findViewById(R.id.button_function)
                    button.text = function[0]
                    if(getTimetableTheme() == 1 && !context!!.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE).getBoolean("night", false)) button.setTextColor(Color.BLACK)
                    button.setOnClickListener {
                        try {
                            val bundle = Bundle()
                            bundle.putString("title",function[0])
                            bundle.putString("url",function[1])
                            activity!!.startActivity(Intent(context, WebViewActivity::class.java).putExtras(bundle))
                        }catch (e: Exception){
                            Toasty.error(context!!, "$e 功能打开失败，请联系开发者反馈").show()
                        }

                    }
                    function_view.addView(view)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if(conn != null){
            activity?.unbindService(conn!!)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == TagHelper.FUNCTION){
            if(resultCode == TagHelper.BANDRR){
                (activity as MainActivity).getTimetableAdapter()?.notifyDataSetChanged()
                UpdateWidgetUtils.updateWidgets(context!!)
            }
        }
    }

}